package com.server.Tcp;

import com.server.utils.TcpSocket;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.HashMap;
import java.util.Map;

import static com.server.utils.TcpSocket.getFixedRes;
@Component
@Slf4j
@Data
public class TcpPool implements CommandLineRunner {
    //存放连接的对象
    public static Map<String,Socket> clientMap=new HashMap<>();
    //连接池能够存放的数量
    private static final int num=5;
    //需要连接的端口号，不能直接注入给静态变量
    private final static int port=Integer.parseInt(getFixedRes("port"));
    /**
     * 功能：添加client进连接池
     */
    public static void addClient(){
        log.info("启动");
        ServerSocket server=null;
        try {
            server = new ServerSocket(port);
            while (true){
                //当出现异常时，直接停止
              //添加客户端进Map,并开启它的读线程和写线程
                if (clientMap.size()<num){
                    try {
                        Socket client=server.accept();
                        if (clientMap.containsKey(client.getInetAddress().getHostAddress())){
                            log.info("重复连接，直接中断");
                            client.close();
                        }else {//未重复连接，正常处理
                            //设置心跳时间60s
                            client.setSoTimeout(60000);
                            clientMap.put(client.getInetAddress().getHostAddress(), client);
                           log.info(client.getInetAddress().getHostAddress()+"已经建立" + (clientMap.size()) + "个连接");
                            //开读线程
                            new ReceiveThread(client).start();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }else {
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            TcpSocket.closeSAndC(null,null,null,null,server,null);
        }
    }

    @Override
    public void run(String... args){
        addClient();
    }
}
